<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import storage from '@/utils/storage'
import { getCategory } from '@/api/goods'

/**
 * 接收父组件传值
 */
const props = defineProps({
  showAlways: {
    // 总是显示下拉分类
    default: false,
    type: Boolean,
  },
  showNavBar: {
    // 显示全部商品分类右侧导航条
    default: true,
    type: Boolean,
  },
  hover: {
    default: false,
    type: Boolean,
  },
  large: {
    // 是否更高的高度
    default: false,
    type: Boolean,
  },
  opacity: {
    // 是否背景透明
    default: false,
    type: Boolean,
  },
  useClass: {
    type: null,
    default: '',
  },
})

const router = useRouter()

// 二级分类展示
const panel = ref(false)
// 二级分类数据
const panelData = ref<Array<any>>([])
// 始终展示一级列表
const showFirstList = ref(false)
// 商品分类
const cateList = ref<any>([])
// 导航列表
const navList = computed(() => {
  if (storage.getNavList())
    return JSON.parse(JSON.stringify(storage.getNavList()))
  else
    return []
})

function showFirstLists(): void {
  showFirstList.value = true
  if (storage.getCategory() && storage.getCategoryExpirationTime()) {
    // 如果缓存过期，则获取最新的信息
    if (Number(new Date()) > Number(localStorage.getItem('category_expiration_time'))) {
      getCate()
      return
    }
    cateList.value = JSON.parse(JSON.stringify(localStorage.getItem('category')))
  }
}
// 获取分类数据
function getCate() {
  if (props.hover)
    return false
  getCategory(0).then((res) => {
    if (res.data.success) {
      cateList.value = res.data.result
      // this.$store.commit("SET_CATEGORY", res.result);
      // 过期时间
      const expirationTime = new Date().setHours(new Date().getHours() + 1)
      // 存放过期时间
      storage.setCategoryExpirationTime(expirationTime)
      // 存放分类信息
      storage.setCategory(JSON.stringify(res.data.result))
    }
  })
}
// 展示全部分类
function showDetail(index: any) {
  panel.value = true
  panelData.value = cateList.value[index].children
}
// 跳转商品列表（分类共有三级，传全部分类过去）
function goGoodsList(id: any, secondId?: any, firstId?: any) {
  const arr = [firstId, secondId, id]
  if (!arr[1])
    arr.splice(0, 2)
  if (!arr[0])
    arr.shift()
  const routerUrl = router.resolve({ path: '/goodsList', query: { categoryId: arr.toString() } })
  window.open(routerUrl.href, '_blank')
}
function linkTo(url: any) {
  if (url.substr(0, 1) === '/') {
    // 非外部链接
    const routeUrl = router.resolve(url)
    window.open(routeUrl.href, '_blank')
  }
  else {
    // 外部链接，完整的url地址
    window.open(url, '_blank')
  }
}

onMounted(() => {
  if (storage.getCategory() && storage.getCategoryExpirationTime()) {
    // 如果缓存过期，则获取最新的信息
    if (Number(new Date()) > Number(storage.getCategoryExpirationTime())) {
      getCate()
      return
    }
    cateList.value = JSON.parse(JSON.stringify(storage.getCategory()))
  }
  else {
    getCate()
  }
})

watch(() => props.showAlways, (val: any) => {
  if (val)
    showFirstLists()
}, { immediate: true, deep: true })
</script>

<template>
  <div class="cate-nav" :class="{ 'fixed-show': useClass === 'fixed-show' }">
    <div class="nav-con" :class="{ 'background-white': useClass === 'background-white' }">
      <div class="all-categories hover-pointer" @mouseenter="showFirstLists" @mouseleave="showFirstList = false">
        商品分类
      </div>
      <ul v-if="showNavBar" class="nav-item">
        <li v-for="(item, index) in navList.list" :key="index" class="nav-list" @click="linkTo(item.url)">
          {{ item.name }}
          <div v-if="index !== navList.list.length - 1" class="colum" />
        </li>
      </ul>
    </div>
    <!-- 全部商品分类 -->
    <div v-show="showAlways || showFirstList" class="cate-list" :style="{ top: !showNavBar ? '60px' : '46px' }"
      @mouseenter="showFirstList = true" @mouseleave="showFirstList = false">
      <!-- 第一级分类 -->
      <div class="nav-side" :class="{ 'large-nav': large, 'opacity-nav': opacity }" @mouseleave="panel = false">
        <ul>
          <li v-for="(item, index) in cateList" :key="index" @mouseenter="showDetail(index)">
            <span class="nav-side-item hover-pointer hover-color" @click="goGoodsList(item.id)">{{ item.name }}</span>
            <span v-for="(second, secIndex) in item.children" :key="secIndex">
              <span v-if="secIndex < 2"> / </span>
              <span v-if="secIndex < 2" class="nav-side-item hover-pointer hover-color"
                @click="goGoodsList(second.id, second.parentId)">{{ second.name }}</span>
            </span>
          </li>
        </ul>
      </div>

      <!-- 展开分类 -->
      <div v-show="panel" class="detail-item-panel" :style="{ minHeight: large ? '470px' : '340px' }"
        @mouseenter="panel = true" @mouseleave="panel = false">
        <div class="nav-detail-item">
          <template v-for="(item, index) in panelData">
            <span v-if="index < 8" :key="index" @click="goGoodsList(item.id, item.parentId)">{{ item.name }}
              <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24">
                <path fill="#999999" d="m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z" />
              </svg>
            </span>
          </template>
        </div>
        <ul>
          <li v-for="(items, index) in panelData" :key="index" class="detail-item-row">
            <span class="detail-item-title" @click="goGoodsList(items.id, items.parentId)">{{ items.name }}
              <svg xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24">
                <path fill="#999999" d="m13.172 12l-4.95-4.95l1.414-1.413L16 12l-6.364 6.364l-1.414-1.415z" />
              </svg>
              <span class="glyphicon glyphicon-menu-right" />
            </span>
            <div>
              <span v-for="(item, subIndex) in items.children" :key="subIndex" class="detail-item"
                @click="goGoodsList(item.id, items.id, items.parentId)">{{ item.name }}</span>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.cate-nav {
  width: 1200px;
  margin: 14px auto 0;
  position: relative;
}

.fixed-show {
  width: 260px;
  margin: 0 !important;

  >.nav-con {
    >.all-categories {
      align-items: center !important;
      height: 60px;
      display: inherit;
      justify-content: center;
      padding: 0 !important;
    }
  }
}

/** 商品分类 */
.nav-con {
  height: 46px;
  margin: 0 auto;
  display: flex;

  .all-categories {
    border-top-left-radius: 10px;
    border-top-right-radius: 10px;
    box-sizing: border-box;
    background: #ffffff;
    width: 260px;
    line-height: 46px;
    font-size: 17px;
    padding-left: 40px;
    color: @text_color;
    letter-spacing: 0;
    flex-shrink: 0;
  }

  .nav-item {
    width: 914px;
    height: 46px;
    border-radius: 10px;
    background: #ffffff;
    margin: 0 0 0 10px;
    line-height: 46px;
    overflow: hidden;
    list-style: none;
    display: flex;

    li.nav-list {
      width: 100px;
      font-size: 17px;
      font-weight: normal;
      color: #333333;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;

      &:hover {
        color: @theme_color;
      }

      .colum {
        height: 14.7px;
        opacity: 1;
        border: 0.7px solid #cbc8c8;
        position: absolute;
        right: 0;
      }
    }

    .nav-list:hover {
      color: @theme_color;
      cursor: pointer;
    }
  }
}

// 分类列表
.cate-list {
  margin: 0 auto;
  position: absolute;
  z-index: 1000;
}

/*展示一级分类*/
.nav-side {
  width: 260px;
  color: #666;
  float: left;
  overflow: hidden;
  border-bottom-left-radius: 10px;
  border-bottom-right-radius: 10px;
  background-color: #fff;
  height: 340px;

  ul {
    width: 100%;
    list-style: none;
    margin-left: -40px;
  }

  li {
    padding: 0 0 16.2px 37.4px;
    font-size: 13px;
    line-height: 18px;
  }
}

/*显示商品详细信息*/
.detail-item-panel {
  width: 1000px;
  min-height: 340px;
  background-color: #fff;
  box-shadow: 0px 0px 15px #ccc;
  position: absolute;
  top: 0;
  left: 200px;
  z-index: 1000;
  padding: 15px;

  >ul {
    margin-left: -40px;
  }

  li {
    line-height: 30px;
  }

  .nav-detail-item {
    margin-top: 5px;
    margin-bottom: 15px;
    cursor: pointer;
    color: #eee;
    display: flex;
  }

  .nav-detail-item span {
    padding: 6px 6px 6px 12px;
    margin-right: 15px;
    font-size: 12px;
    color: #333;
    display: flex;
    align-items: flex-end;
  }

  .nav-detail-item span:hover {
    background-color: @theme_color;
    color: #fff;
  }

  .detail-item-row {
    display: flex;
    align-items: flex-start;

    >div {
      flex: 1;
    }

    .detail-item-title {
      font-weight: bold;
      font-size: 12px;
      cursor: pointer;
      color: #555555;
      padding-right: 10px;
      width: 81px;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }

    .detail-item-title:hover {
      color: @theme_color;
    }

    .detail-item {
      font-size: 12px;
      padding-left: 8px;
      padding-right: 8px;
      cursor: pointer;
      border-left: 1px solid #ccc;
      color: #515a6e;

      &:first-child {
        border: none;
        padding-left: 0;
      }
    }

    .detail-item:hover {
      color: @theme_color;
    }
  }
}
</style>
